package com.wufeng.intercepter;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wufeng.utils.JwtUtils;
import org.json.JSONObject;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JwtIntercepter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();

        //获取请求头中的令牌
        String token = request.getHeader("Authorization");
        System.out.println(token);

        //验证令牌
        try {
            if (token == null || token == "") {
                map.put("msg", "无效令牌");
                String json = new ObjectMapper().writeValueAsString(map);
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().println(json);//将json写入响应
                return false;
            }
            JwtUtils.verify(token);//验证令牌
            return true;
        } catch (StringIndexOutOfBoundsException e) {
            e.printStackTrace();
            map.put("msg", "无效签名");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg", "token过期");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg", "token算法不一致");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "token验证失败");
        }
        map.put("state", 400);//设置状态
        //将map转为json
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(json);//将json写入响应体

        System.out.println("进入jwt拦截器");
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
